package com.yhuk.oauth.server.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author xiaolang
 * @version 1.0.0
 */
@Configuration
@Order(1)
@MapperScan(basePackages = "com.yhuk.oauth.server.dao.power", sqlSessionTemplateRef = "powerSqlSessionTemplate")
public class PowerDataSourceConfig {

    /**
     * 配置数据源
     * @return
     */
    @Bean(name = "powerDataSource")
    @ConfigurationProperties("spring.datasource.power")
    public DataSource powerDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 配置session工厂
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "powerSqlSessionFactory")
    public SqlSessionFactory powerSqlSessionFactory(@Qualifier("powerDataSource") DataSource dataSource) throws  Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
//        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:"));
        return bean.getObject();
    }

    /**
     * 配置事务
     * @param dataSource
     * @return
     */
    @Bean(name = "powerTransactionManager")
    public DataSourceTransactionManager powerTransactionManager(@Qualifier("powerDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 模版
     * @param sqlSessionFactory
     * @return
     */
    @Bean(name = "powerSqlSessionTemplate")
    public SqlSessionTemplate powerSqlSessionTemplate(@Qualifier("powerSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
